package com.jiashihui.web.controller;

import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
public class FileDownloadController {

    /**
     * 文件下载
     * @param file file带后缀：file.text、file.zip
     * @param permission 权限加密字符串，校验（session）
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/path/{file:.+}")
    public void download(@PathVariable("file") String file, String permission, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String basePath = "";
        try(InputStream inputStream =  new FileInputStream(new File(basePath, file));
            OutputStream outputStream = response.getOutputStream()){
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + file);
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}
